from pynput.mouse import Controller, Button
from pynput.keyboard import Controller as KeyboardController, Key
import tkinter as tk
import time

# 初始化鼠标和键盘控制器
mouse = Controller()
keyboard = KeyboardController()

# 设置目标坐标
input_box_position = (700, 830)  # 输入框位置 (x, y)

# 模拟鼠标点击输入框并输入内容
def click_and_type(text):
    try:
        # 鼠标移动到输入框位置并点击
        mouse.position = input_box_position
        time.sleep(0.5)  # 等待鼠标移动完成
        mouse.click(Button.left)

        # 模拟键盘输入
        time.sleep(0.5)  # 等待输入框获取焦点
        keyboard.type(text)

        # 模拟按下回车键
        time.sleep(0.5)
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)
    except Exception as e:
        print(f"发生错误: {e}")

# 循环执行任务
def execute_tasks():
    for i, sentence in enumerate(sentences):
        result_label.config(text=f"正在输入第 {i+1}/{len(sentences)} 行")
        root.update()  # 刷新 GUI 界面
        click_and_type(sentence)
        time.sleep(3)  # 每次输入间隔 1 秒
    result_label.config(text="所有任务已完成！", fg="green")

# 退出程序
def exit_program():
    root.destroy()

# 从文件中读取文本
def read_sentences(filename):
    with open(filename, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    cleaned_lines = [line.strip() for line in lines if line.strip()]
    return cleaned_lines

# 读取文件内容
filename = "question.txt"
sentences = read_sentences(filename)

# 创建 GUI 界面
root = tk.Tk()
root.title("鼠标键盘模拟器")
root.geometry("300x200")

# 设置窗口置顶
root.attributes('-topmost', True)

# 按钮和结果提示
action_button = tk.Button(root, text="执行任务", command=execute_tasks, width=20, height=2)
action_button.pack(pady=10)

exit_button = tk.Button(root, text="退出", command=exit_program, width=20, height=2)
exit_button.pack(pady=10)

result_label = tk.Label(root, text="", fg="red")
result_label.pack(pady=10)

# 运行主循环
root.mainloop()
